package com.netbliz.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;



/**
 * 加密工具类
 * @author jyxiao
 *
 */
public class EncryptionUtil {
	private static org.apache.log4j.Logger logger=Logger.getLogger(EncryptionUtil.class);
	/**
	 * 返回经MD5加密后的数据，如失败将返回null
	 * @param source：源数据
	 * @return
	 */
	public static String getMD5(String source){
		if(source==null || source.trim().equals("")){
			return null;
		}
		StringBuffer md5StringBuffer=new StringBuffer();
		MessageDigest messageDigest=null;
		try {
			messageDigest=MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(source.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			logger.error("未发现MD5算法！");
		} catch (UnsupportedEncodingException e) {
			logger.error("源数据采用UTF-8编码时出错！");
		}
		if(null!=messageDigest){
			byte[] byteArray = messageDigest.digest();  
	        for (int i = 0; i < byteArray.length; i++) {              
	            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
	            	md5StringBuffer.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
	            else  
	            	md5StringBuffer.append(Integer.toHexString(0xFF & byteArray[i]));  
	        }
			return md5StringBuffer.toString();
		}
		return null;
	}
	public static void main(String[] args) {
		System.out.println(getMD5("ceode"));
	}
}
